package com.hxd.mall.module.product.search.adapter

import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.graphics.drawable.toBitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.RequestOptions.bitmapTransform
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.hxd.mall.R
import com.hxd.mall.module.product.home.bean.ListBean
import com.hxd.mall.utils.open.StringUtil
import com.hxd.mall.utils.open.StringUtil.setIconText
import com.hxd.mall.utils.open.ViewUtils
import com.hxd.mall.utils.open.load
import com.hxd.mall.utils.open.setIconAndText
import com.hxd.mall.widget.CenterCropRoundCornerTransform
import com.shizhefei.view.largeimage.LargeImageView
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics
import android.graphics.Bitmap
import android.graphics.Matrix
import com.hxd.mall.constant.HxdConstants
import com.hxd.mall.constant.HxdConstantsRouterPath
import com.hxd.mall.utils.local.NavigationUtil


class SearchListAdapter(resLayout: Int? = R.layout.adapter_search_list_item_layout) : BaseQuickAdapter<ListBean, BaseViewHolder>(resLayout ?: R.layout.adapter_search_list_item_layout) {
    override fun convert(helper: BaseViewHolder?, item: ListBean?) {
        val totalPrice = helper?.getView<TextView>(R.id.originPrice)
        totalPrice?.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
        totalPrice?.text =
            if ("tmall" == item?.subChannel) {
                "天猫价:${item?.reservePrice}"
            } else {
                "淘宝价:${item?.reservePrice}"
            }
        helper?.run {
            setText(R.id.price, item?.discountPrice.toString())
            setText(R.id.discountPrice, "${item?.couponInfo}")
            setText(R.id.recive, "${item?.estimatedIncome}")
            setText(R.id.price_num, "${item?.volume}人付款")

            setGone(R.id.tv_shopName_city, item?.shopName != null && item.shopName.isNotEmpty())
            setText(R.id.tv_shopName_city, "${item?.shopName?.trim()}\t${item?.provCity}")

            ViewUtils.isHidden(item?.couponInfo, getView<TextView>(R.id.discountPrice))
            ViewUtils.isHidden(item?.estimatedIncome, getView(R.id.recive))
            StringUtil.setSize(this.getView(R.id.price), "${item?.discountPrice.toString()}")

            setIconText(getView<TextView>(R.id.productTitle), getView<ImageView>(R.id.iv_logo_icon), item?.subChannel ?: "", item?.title.toString())

            val view = getView<View>(R.id.leftImg).apply {
                setOnClickListener {
                    NavigationUtil.routerNavigation(
                        HxdConstantsRouterPath.Product.path_hxd_product_detail_page,
                        mutableMapOf(HxdConstants.IntentParamsKeyDefine.product_skuNo to (item?.no?:""))
                    )
                }
            }
            //图片加载
            val requestManager = Glide.with(mContext)
            view.setTag(view.id, requestManager)

            val requestOptions = bitmapTransform(CenterCropRoundCornerTransform(15))
            try {
                val imageView = getView<LargeImageView>(R.id.leftImg)
                requestManager.load(item?.pictUrl ?: "").apply(requestOptions.placeholder(R.mipmap.product_item_icon)).into(object : SimpleTarget<Drawable>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        imageView.setImage(resource)
                    }
                    override fun onStart() {
                        super.onStart()
                        imageView.setImage(R.mipmap.product_item_icon)
                    }
                })
            } catch (e: Exception) {
                requestManager.load(item?.pictUrl ?: "").apply(requestOptions.placeholder(R.mipmap.product_item_icon).error(R.mipmap.product_item_icon))
                    .into(view as ImageView)
            }
        }
    }

//    /**
//     * 按比例缩放图片
//     *
//     * @param origin 原图
//     * @param ratio  比例
//     * @return 新的bitmap
//     */
//    private fun scaleBitmap(origin: Bitmap?, ratio: Float): Bitmap? {
//        if (origin == null) {
//            return null
//        }
//        val width = origin.width
//        val height = origin.height
//        val matrix = Matrix()
//        matrix.preScale(ratio, ratio)
//        val newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false)
//        if (newBM == origin) {
//            return newBM
//        }
//        // origin.recycle()
//        return newBM
//    }

    override fun onViewRecycled(holder: BaseViewHolder) {
        super.onViewRecycled(holder)

        //每次复用时先断开之前的请求
        val imageView = holder.getView<View>(R.id.leftImg) ?: return
        val requestManager = imageView.getTag(imageView.id) as RequestManager
        requestManager.clear(imageView)
    }


    /*由于Java是基于Unicode编码的，因此，一个汉字的长度为1，而不是2。
     * 但有时需要以字节单位获得字符串的长度。例如，“123abc长城”按字节长度计算是10，而按Unicode计算长度是8。
     * 为了获得10，需要从头扫描根据字符的Ascii来获得具体的长度。如果是标准的字符，Ascii的范围是0至255，如果是汉字或其他全角字符，Ascii会大于255。
     * 因此，可以编写如下的方法来获得以字节为单位的字符串长度。*/
    fun getWordCount(s: String): Int {
        var length = 0
        for (i in 0 until s.length) {
            val ascii = Character.codePointAt(s, i)
            if (ascii in 0..255)
                length++
            else
                length += 2
        }
        return length
    }

}